﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SheepClock.CustomUIComponents
{
    public partial class Switch : UserControl
    {
        private bool mIsON;
        public bool IsON
        {
            get
            {
                return mIsON;
            }
            set
            {
                mIsON = value;
                if (mIsON)
                {
                    FillRect.Opacity = 1;
                    Slider.Margin = new Thickness(56, 0, 0, 0);
                }
                else
                {
                    FillRect.Opacity = 0;
                    Slider.Margin = new Thickness(4, 0, 0, 0);
                }
            }
        }

        public event EventHandler<SwitchStateArgs> StateChanged;

        public Switch()
        {
            InitializeComponent();

            this.MouseLeftButtonDown += new MouseButtonEventHandler(Switch_MouseLeftButtonDown);
        }

        void Switch_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            mIsON = !mIsON;
            UpdateVisualState(true);
        }

        private void UpdateVisualState(bool withAnimation)
        {
            string storyBoardName;
            Slider.Margin = new Thickness(4, 0, 0, 0);
            if (mIsON)
                storyBoardName = "TurnONStoryboard";
            else
                storyBoardName = "TurnOFFStoryboard";

            Storyboard storyBoard;
            storyBoard = (Storyboard)this.Resources[storyBoardName];
            if (withAnimation)
                storyBoard.Duration = new TimeSpan(0, 0, 0, 0, 500);
            else
                storyBoard.Duration = new TimeSpan(0);
            storyBoard.Begin();

            if (StateChanged != null)
                StateChanged(this, new SwitchStateArgs(mIsON));
        }

        public class SwitchStateArgs : EventArgs
        {
            public SwitchStateArgs(bool isOn)
            {
                this.IsOn = isOn;
            }

            public bool IsOn
            {
                get;
                set;
            }
        }

    }
}